<?

/* --|	POSTIE
  Software: Socially
  Version: 1.0
  Contact: http://socially.googlecode.com
  Info: http://socially.googlecode.com
  Support: http://socially.googlecode.com
  --------------------------------------------------------------------------
  Author: goker.cebeci | http://gokercebeci.com
  --------------------------------------------------------------------------
  License: Distributed under the GNU General Public License (GPL)
  http://www.gnu.org/licenses/gpl.html
  This program is distributed in the hope that it will be useful - WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.
  ------------------------------------------------------------------------- */

class postie {

    public static function send($a) {
        $a['title'] = strip_tags(addslashes(trim($a['title'])));
        $a['message'] = strip_tags(addslashes(trim($a['message'])));
        if (!$a['message'])
            return common::result(400, _('Please write a message.'), array('message'));
        if ($a['RID']) {
            $sender = profile::get(array('ID' => $a['UID']));
            db::query(sprintf("INSERT INTO postieConversations (title) VALUES ('%s');", $a['title']));
            $CID = db::insertid();
            db::query(sprintf("INSERT INTO postieMessages (conversationID,message,date) VALUES ('%d','%s',NOW());", $CID, $a['message']));
            $MID = db::insertid();
            db::query(sprintf("INSERT INTO postieAttendees (conversationID,senderID,recipientID,messageID,status) VALUES ('%d','%d','%d','%d','%d');", $CID, $a['UID'], $a['RID'], $MID, 0));
            // check online
            //if (account::status($a['RID']) == 'offline') {
                //notification mail
                $message = sprintf(_('You have a new message from %s.<br /> %sclick here to read%s.'),
                                '<a href="http://' . DOMAIN . '/' . $sender->url . '">' . $sender->name . '</a>',
                                '<a href="http://' . DOMAIN . '/' . LANG . '/postie/conversation/' . $CID . '">', '</a>');
                notification::mail(array('application' => 'postie', 'sender' => $a['UID'], 'recipient' => $a['RID'], 'message' => $message));
            //}
            return common::result(200, _('Your message has been sent.'), null, '/' . LANG . '/postie/outbox'); // array(301,$a['UID'],$a['RID'],$MID));
        } else
            return common::result(800, _('Recipient ID is null!'));
    }

    public static function reply($a) {
        $a['message'] = strip_tags(addslashes(trim($a['message'])));
        if (!$a['message'])
            return common::result(400, _('Please write a message.'), array('message'));
        if ($a['CID']) {
            $sender = profile::get(array('ID' => $a['UID']));
            db::query(sprintf("INSERT INTO postieMessages (conversationID,message,date) VALUES ('%d','%s',NOW());", $a['CID'], $a['message']));
            $MID = db::insertid();
            foreach (self::attendees($a) as $r)
                db::query(sprintf("UPDATE postieAttendees SET status = 1 WHERE recipientID = %d AND conversationID = %d;", $r->RID, $a['CID']));
            db::query(sprintf("INSERT INTO postieAttendees (conversationID,senderID,recipientID,messageID,status) VALUES ('%d','%d','%d','%d',0);", $a['CID'], $a['UID'], $r->RID, $MID));
            // check online
            //if (account::status($r->RID) == 'offline') {
                //notification mail
                $message = sprintf(_('You have a new message from %s.<br /> %sclick here to read%s.'),
                                '<a href="http://' . DOMAIN . '/' . $sender->url . '">' . $sender->name . '</a>',
                                '<a href="http://' . DOMAIN . '/' . LANG . '/postie/conversation/' . $a['CID'] . '">', '</a>');
                notification::mail(array('application' => 'postie', 'sender' => $a['UID'], 'recipient' => $r->RID, 'message' => $message));
            //}
            //return common::result(200,_('Your message has been sent.'),null,'/'.LANG.'/postie/conversation/'.$a['CID']);// array(302,$a['UID'],$r->RID,$MID));

            $i = new stdClass();
            $i->sender = $p = $sender;
            $i->message = stripslashes($a['message']);
            //$tpl = str_replace(array('<?=','>'),'',file_get_contents('apps/postie/template/_item.html'));
            $tpl = common::template('apps/postie/template/_item.html', $i, $p);
            return common::result(200, json_encode($tpl)); // array(302,$a['UID'],$r->RID,$MID));
        } else
            return common::result(800, _('Conversation ID is null!'));
    }

    public static function delete($a) {
        if ($a['sender'])
            db::query(sprintf("UPDATE postieAttendees SET status = 2 WHERE senderID = %d AND conversationID = %d;", $a['UID'], $a['CID']));
        else
            db::query(sprintf("UPDATE postieAttendees SET status = 2 WHERE recipientID = %d AND conversationID = %d;", $a['UID'], $a['CID']));
        return common::result(200, array(303, $a['UID'], 0, $a['CID']));
    }

    public static function read($a) {
        db::query(sprintf("UPDATE postieAttendees SET status = 1 WHERE status = 0 AND conversationID = %d AND recipientID = %d;", $a['CID'], $a['UID']));
        if ($a['earlier']) {
            $c = db::query(sprintf("SELECT c.ID, c.title, a.senderID,
            (SELECT `message` FROM postieMessages WHERE ID = a.messageID) as `message`,
            (SELECT `date` FROM postieMessages WHERE ID = a.messageID) as `date`
            FROM postieConversations as c, postieAttendees as a
            WHERE c.ID = a.conversationID  AND c.ID = %d AND (senderID = %d OR recipientID = %d)  ORDER BY a.`ID` DESC LIMIT 10,1000;", $a['CID'], $a['UID'], $a['UID']), true, true);
            if ($c)
                foreach (array_reverse($c) as $k => $i) {
                    $i->sender = profile::get(array('ID' => $i->senderID));
                    $tpl .= common::template('apps/postie/template/_item.html', $i, $p);
                }
            return common::result(200, json_encode($tpl));
        } else {
            $c = db::query(sprintf("SELECT c.ID, c.title, a.senderID,
            (SELECT `message` FROM postieMessages WHERE ID = a.messageID) as `message`,
            (SELECT `date` FROM postieMessages WHERE ID = a.messageID) as `date`
            FROM postieConversations as c, postieAttendees as a
            WHERE c.ID = a.conversationID  AND c.ID = %d AND (senderID = %d OR recipientID = %d)  ORDER BY a.`ID` DESC LIMIT 11;", $a['CID'], $a['UID'], $a['UID']), true, true);
            if ($c)
                foreach ($c as $k => $i) {
                    $c[$k]->sender = $p = profile::get(array('ID' => $i->senderID));
                }
            if (($t = count($c)) > 10)
                $c[$t - 1]->earlier = true;
        }
        return $c;
    }

    public static function conversations($a) {
        if ($a['type'] == 'inbox')
            $c = db::query(sprintf("SELECT c.ID, c.title, a.senderID,
        (SELECT COUNT(ID) FROM postieAttendees WHERE messageID = MAX(a.messageID) AND `status` = 0) as `unread`,
        (SELECT `message` FROM postieMessages WHERE ID = MAX(a.messageID) ) as `message`,
        (SELECT `date` FROM postieMessages WHERE ID = MAX(a.messageID) ) as `date`
        FROM postieConversations as c, postieAttendees as a WHERE a.status < 2 AND c.ID = a.conversationID AND a.recipientID = %d GROUP BY a.conversationID ORDER BY `date` DESC LIMIT 30;", $a['UID']), true, true);
        else
            $c = db::query(sprintf("SELECT c.ID, c.title, a.recipientID,
        (SELECT `message` FROM postieMessages WHERE ID = MAX(a.messageID) ) as `message`,
        (SELECT `date` FROM postieMessages WHERE ID = a.messageID ) as `date`
        FROM postieConversations as c, postieAttendees as a WHERE a.status < 2 AND c.ID = a.conversationID AND a.senderID = %d GROUP BY a.conversationID ORDER BY a.ID DESC LIMIT 30;", $a['UID']), true, true);
        if ($c)
            foreach ($c as $k => $i) {
                if ($a['type'] == 'inbox')
                    $c[$k]->sender = profile::get(array('ID' => $i->senderID));
                else
                    $c[$k]->recipient = profile::get(array('ID' => $i->recipientID));
            }
        return $c;
    }

    public static function attendees($a) {
        $r = db::query(sprintf("SELECT recipientID as RID FROM postieAttendees WHERE conversationID = %d AND recipientID <> %d GROUP BY recipientID;", $a['CID'], $a['UID']), true, true);
        return (count($r)) ? $r : db::query(sprintf("SELECT senderID as RID FROM postieAttendees WHERE conversationID = %d ORDER BY ID ASC LIMIT 1;", $a['CID']), true, true);
    }

    public static function unread($a) {
        return db::query(sprintf("SELECT COUNT(ID) as unread FROM postieAttendees  WHERE recipientID = %d AND status = 0;", $a), true);
    }

}

?>